package com.wenan.ui.reports
{
	import com.wenan.AppGlobal;
	import com.wenan.data.DataUtil;
	import com.wenan.data.PageInfo;
	import com.wenan.data.Parameter;
	import com.wenan.data.ParameterCollection;
	import com.wenan.data.PositionType;
	import com.wenan.ui.controls.dateChooser.DateUtil;
	
	import flash.events.EventDispatcher;
	import flash.net.registerClassAlias;
	import flash.utils.ByteArray;
	import flash.utils.getDefinitionByName;
	import flash.utils.getQualifiedClassName;
	
	import mx.collections.ArrayCollection;
	import mx.controls.Alert;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;

	public class ReportDataFactory extends EventDispatcher
	{
		private var reportName:String;
		private var pageInfo:PageInfo = new PageInfo();
		public function ReportDataFactory()
		{
		}
		
		/**
		 * 获取默认报表选项数据
		 * */
		public function getReportItemData(reportName:String):void
		{
			this.reportName = reportName;
			AppGlobal.dataLayer.getDefaultReportItemData(reportName, reportResultHandler, null, true, false);
		}
		
		protected function reportResultHandler(event:ResultEvent):void
		{
			var result:Object = event.result as Object;
			
			pageInfo.pageName = "Report";
			pageInfo.positionType = PositionType.REPORT;
			var parameters:ParameterCollection = new ParameterCollection();
			parameters.add(new Parameter("date", result.date));
			parameters.add(new Parameter("datetype", result.datetype));
			parameters.add(new Parameter("resname", result.resname));
			parameters.add(new Parameter("default_report_type", result.default_report_type));
			parameters.add(new Parameter("other_report_type", result.other_report_type));
			parameters.add(new Parameter("ReportType", DataUtil.formatPageName(result.default_report_type)));
			parameters.add(new Parameter("dataurl", result.dataurl));
			parameters.add(new Parameter("navIndex","1"));//导航栏下标
			parameters.add(new Parameter("navName", reportName));//导航栏下标
			//广场选择
			var ids:String = "";
			var idsArray:ArrayCollection = new ArrayCollection(result.res as Array);
			var isSelected:Boolean = false;
			for each (var obj:Object in idsArray)
			{
				if ((obj.selected as String) == "true")
				{
					isSelected = true;
					obj.selected = true;
				} else 
				{
					obj.selected = false;
				}
				if (isSelected)
				{
					ids += obj.id + ",";
				}
				isSelected = false;
			}
			ids = ids.substr(0, ids.length - 1);
			parameters.add(new Parameter("res", null, idsArray));
			//拼凑报表类型(已经转成中文了)
			var chartType:String = "";
			var defaultReportType:String = result.default_report_type;
			chartType += DataUtil.formatPageName(result.default_report_type) + ",";
			var otherReport:String = result.other_report_type as String;
			if (otherReport && otherReport != "")
			{
				var drt:Array = otherReport.split(",");
				if (drt && drt.length > 0)
				{
					for each (var str:String in drt)
					{
						chartType += DataUtil.formatPageName(str) + ",";
					}
				}
			}
			chartType = chartType.substr(0, chartType.length - 1);
			parameters.add(new Parameter("chartType", chartType));//导航栏下标
			//指标
			var columns:String = "";
			var columnsArray:ArrayCollection = new ArrayCollection(result.datalist as Array);
			var yColumnArray:ArrayCollection = clone(columnsArray) as ArrayCollection;
			if (columnsArray && columnsArray.length > 0)
			{
				if (defaultReportType == "scatter")
				{
					for (var i:int=0; i<columnsArray.length; i++)
					{
						if (columnsArray.getItemAt(i).selected == "true")
						{
							isSelected = true;
							if (i == 0)
							{
								columnsArray.getItemAt(i).selected = true;
							} else 
							{
								columnsArray.getItemAt(i).selected = false;
							}
						} else 
						{
							columnsArray.getItemAt(i).selected = false;
						}
						if (isSelected)
						{
							columns += columnsArray.getItemAt(i).key + ",";
						}
						isSelected = false;
					}
					for (var j:int=0; j<yColumnArray.length; j++)
					{
						if (yColumnArray.getItemAt(j).selected == "true")
						{
							if (j == 1)
							{
								yColumnArray.getItemAt(j).selected = true;
							} else 
							{
								yColumnArray.getItemAt(j).selected = false;
							}
						} else 
						{
							yColumnArray.getItemAt(j).selected = false;
						}
					}
					columns = columns.substr(0, columns.length - 1);
					parameters.add(new Parameter("xdatalist", null, columnsArray));
					parameters.add(new Parameter("ydatalist", null, yColumnArray));
				} else 
				{
					for each (var o:Object in columnsArray)
					{
						if ((o.selected as String) == "true")
						{
							isSelected = true;
							o.selected = true;
						} else 
						{
							o.selected = false;
						}
						if (isSelected)
						{
							if (defaultReportType == "line")
							{
								columns += o.key + ",";
							} else 
							{
								columns += o.key + " " + o.sort + ",";
							}
						}
						isSelected = false;
					}
					columns = columns.substr(0, columns.length - 1);
					parameters.add(new Parameter("datalist", null, columnsArray));
				}
			}
			
			var isquery:String = result.isquery as String;
			parameters.add(new Parameter("isquery", isquery));
			pageInfo.parameters = parameters;
			if (isquery == "true")
			{
				queryReportData(result.dataurl, result.resname, result.date, result.datetype, ids, columns, chartType, pageInfo);
			}
		}
		
		/**
		 * 查询报表数据
		 * */
		public function queryReportData(url:String, resname:String, date:String, datetype:String, ids:String, columns:String, charttype:String, pageInfo:PageInfo):void
		{
			AppGlobal.dataLayer.queryReportData(url, resname, date, datetype, ids, columns, charttype, function(e:ResultEvent):void {
				var result:Object = e.result as Object;
				var chartsytle:Array = result.Chartstyle as Array;
				
				var dataProvider:ArrayCollection = new ArrayCollection(result.Chartdata as Array);
				//保证每次查询都是最新的，而且是唯一的。
				if (pageInfo.parameters.findByName("dataProvider")) 
				{
					pageInfo.parameters.removeByName("dataProvider");
				}
				if (pageInfo.parameters.findByName("reportStyle")) 
				{
					pageInfo.parameters.removeByName("reportStyle");
				}
				pageInfo.parameters.add(new Parameter("dataProvider", null, dataProvider));
				pageInfo.parameters.add(new Parameter("reportStyle", null, getChartStyle(chartsytle)));
				dispatchEvent(new ReportDataEvent(ReportDataEvent.REPORTDATA, pageInfo));
			
			}, function(event:FaultEvent):void {
//				dispatchEvent(new ReportDataEvent(ReportDataEvent.REPORTDATA, pageInfo));
//				Alert.show("数据获取错误，请联系管理员！"); 
			}, false, true);
		}
		
		public function getChartStyle(chartsytle:Array):ParameterCollection
		{
			if (chartsytle && chartsytle.length > 0)
			{
				var charts:ParameterCollection = new ParameterCollection();
				var values:ParameterCollection;
				var ySelectableFields:ArrayCollection;
				var yDefaultFields:ArrayCollection;
				var xDefaultField:String
				var reportStyle:Object;
				var type:String;
				var field:Object;
				var legends:ArrayCollection
				for each (var obj:Object in chartsytle)
				{
					values = new ParameterCollection();
					ySelectableFields = new ArrayCollection();
					yDefaultFields = new ArrayCollection();
					type = obj.Type;
					reportStyle = new Object();
					reportStyle.type = type;
					reportStyle.title = obj.Title;
					
					if (type == "表格")
					{
						legends = new ArrayCollection(obj.Legend as Array);
						if (legends && legends.length > 0)
						{
							
							for each (var o:Object in legends)
							{
								field = new Object();
								field.title = o.text;
								field.propertyName = o.valueField;
								yDefaultFields.addItem(field);
							}
						}
						xDefaultField = "name";
					} else if (type == "簇状图" || type == "线状图")
					{
						legends = new ArrayCollection(obj.Legend as Array);
						if (legends && legends.length > 0)
						{
							
							for each (var o1:Object in legends)
							{
								field = new Object();
								field.title = o1.Text;
								field.propertyName = o1.valueField;
								field.color = DataUtil.convertColor(o1.color);
								yDefaultFields.addItem(field);
							}
						}
						xDefaultField = obj.AxisX.categoryField;
						reportStyle.axisX = obj.AxisX.Text + axisUnitStyle(obj.AxisX.Unit);
						reportStyle.axisY = obj.AxisY.Text + axisUnitStyle(obj.AxisY.Unit);
						
					} else if (type == "柱状图")
					{
						var legend:Object = obj.Legend;
						field = new Object();
						field.title = legend.Text;
						field.propertyName = legend.valueField;
						field.color = DataUtil.convertColor(legend.color);
						yDefaultFields.addItem(field);
						xDefaultField = "name";
						reportStyle.axisX = obj.AxisX.Text + axisUnitStyle(obj.AxisX.Unit);
						reportStyle.axisY = obj.AxisY.Text + axisUnitStyle(obj.AxisY.Unit);
					} else if (type == "散点图")
					{
						var xfield:Object = new Object();
						xfield.propertyName = obj.AxisX.xField;
						var yfield:Object = new Object();
						yfield.propertyName = obj.AxisY.yField;
						yDefaultFields.addItem(xfield);
						yDefaultFields.addItem(yfield);
						reportStyle.axisX = obj.AxisX.Text + axisUnitStyle(obj.AxisX.Unit);
						reportStyle.axisY = obj.AxisY.Text + axisUnitStyle(obj.AxisY.Unit);
						reportStyle.balloonText = obj.AxisX.Text;
					}
					values.add(new Parameter("xSelectableFields", null, yDefaultFields));
					values.add(new Parameter("ySelectableFields", null, yDefaultFields));
					values.add(new Parameter("xDefaultField", null, xDefaultField));
					values.add(new Parameter("yDefaultFields", null, yDefaultFields));
					values.add(new Parameter("reportStyle", null, reportStyle));
					charts.add(new Parameter(type, null, values));
				}
				return charts;
			}
			return null;
		}
		
		private function axisUnitStyle(value:String):String
		{
			if (value && value != "")
			{
				return "(" + value + ")";
			} else 
			{
				return value;
			}
		}
		
		
		/**
		 * 构造ids 如广场id(selected以字符串构造)
		 * */
		public function buildIdsByBoolean(idsArray:ArrayCollection):String
		{
			var ids:String = "";
			var isSelected:Boolean = false;
			for each (var obj:Object in idsArray)
			{
				if (obj.selected)
				{
					ids += obj.id + ",";
				}
			}
			ids = ids.substr(0, ids.length - 1);
			return ids;
		}
		
		/**
		 * 构造指标(selected以字符串构造)
		 * */
		public function buildColumnsByBoolean(columnsArray:ArrayCollection, defaultReportType:String, yArray:ArrayCollection = null):String
		{
			var columns:String = "";
			if (columnsArray && columnsArray.length > 0)
			{
				if (defaultReportType == "scatter")
				{
					for each (var o1:Object in columnsArray)
					{
						if (o1.selected)
						{
							columns += o1.key + ",";
							break;
						}
					}
					for each (var o2:Object in yArray)
					{
						if (o2.selected)
						{
							columns += o2.key + ",";
							break;
						}
					}
				} else 
				{
					for each (var o:Object in columnsArray)
					{
						if (o.selected)
						{
							if (defaultReportType == "line")
							{
								columns += o.key + ",";
							} else 
							{
								columns += o.key + " " + o.sort + ",";
							}
						}
					}
				}
				columns = columns.substr(0, columns.length - 1);
				return columns;
			}
			return "";
		}
		
		/**
		 * flex克隆对象
		 * */
		public function clone(object:Object):Object
		{
			var qClassName:String = getQualifiedClassName(object);
			var objectType:Class = getDefinitionByName(qClassName) as Class;
			registerClassAlias(qClassName, objectType);
			var copier : ByteArray = new ByteArray();
			copier.writeObject(object);
			copier.position = 0;
			return copier.readObject();
		}
		
		public function setReportData(currentPageInfo:PageInfo):void
		{
			var url:String = currentPageInfo.parameters.getValue("dataurl");
			var resname:String = currentPageInfo.parameters.getValue("resname");
			var date:String = currentPageInfo.parameters.getValue("date");
			var datetype:String = currentPageInfo.parameters.getValue("datetype");
			var default_report_type:String = currentPageInfo.parameters.getValue("default_report_type");
			var ids:String = buildIdsByBoolean(currentPageInfo.parameters.getObj("res") as ArrayCollection);
			var columns:String;
			if (default_report_type == "scatter")
			{
				columns = buildColumnsByBoolean(currentPageInfo.parameters.getObj("xdatalist") as ArrayCollection, default_report_type, currentPageInfo.parameters.getObj("ydatalist") as ArrayCollection);
			} else 
			{
				columns = buildColumnsByBoolean(currentPageInfo.parameters.getObj("datalist") as ArrayCollection, default_report_type);
			}
			var charttype:String = currentPageInfo.parameters.getValue("chartType");
			
			this.addEventListener(ReportDataEvent.REPORTDATA, function(event:ReportDataEvent):void {
				AppGlobal.modulePageContainer.navigate(event.pageInfo, true);	
			});
			
			queryReportData(url, resname, date,datetype, ids, columns, charttype, currentPageInfo);
			
		}
	}
}